package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@org.aspectj.lang.annotation.Aspect
@Component
@Slf4j
public class AspectFill {

    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
  public void autoAspectFill(){}

    @Before("autoAspectFill()")
        public void autoFill(JoinPoint joinPoint) throws Exception {
            log.info("开始公共字段填充");

        //获取到当前被拦截的方法上的数据库操作类型
         MethodSignature  signature = (MethodSignature) joinPoint.getSignature();
         AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
         OperationType value = annotation.value();

        //获取到当前被拦截的方法的参数--实体对象
         Object[] argss = joinPoint.getArgs();
       Object args =   argss[0];

        //准备赋值的数据
         LocalDateTime now = LocalDateTime.now();
         Long currentId = BaseContext.getCurrentId();
        //根据当前不同的操作类型，为对应的属性通过反射来赋值
        if(value == OperationType.INSERT){
                 Method declaredMethod1 = args.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method declaredMethod2= args.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER,Long.class);
                Method declaredMethod3 =args.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
                Method declaredMethod4= args.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);
                declaredMethod1.invoke(args,now);
                declaredMethod2.invoke(args,currentId);
                declaredMethod3.invoke(args,now);
                declaredMethod4.invoke(args,currentId);
        }else if(value==OperationType.UPDATE){
                Method declaredMethod3 =args.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
                Method declaredMethod4= args.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);
                declaredMethod3.invoke(args,now);
                declaredMethod4.invoke(args,currentId);
            }
        }
    }

